<template>
  <div class="loginpage">
    <div class="l-h">
      <img class="img1" src="//chengguo-1309318813.cos.ap-beijing.myqcloud.com/uploads/zizhi/1733658423176%E9%A1%B5%E7%9C%89.png" alt="">
      <div class="l-h-r" @click="to('/')">
        <img src="//chengguo-1309318813.cos.ap-beijing.myqcloud.com/uploads/zizhi/1733658505979%E9%A6%96%E9%A1%B5%2C%E5%B1%8B%E5%AD%90%2C%E4%B8%BB%E9%A1%B5%2C%E6%88%BF%E5%AD%90.png" alt="">
        <div class="back">返回首页</div>
      </div>

    </div>
    <div class="l-c">
      <div class="l-c-l">
        <div class="l1">站院协同服务平台</div>
        <div class="l2">如果您是首次登录站院协同服务平台</div>
        <div class="l2">请点击下方"立即注册"按钮进行在线注册</div>
        <div class="regis" @click="to('/register')">
          立即注册
        </div>
      </div>
      <div class="login-modal">
        <div class="r">
          <div class="divc">{{ loginMode == loginModeEnum.Login ? '登 录' : '重置密码' }}</div>
          <el-form
            style="width: 100%;"
            ref="formRef"
            :model="dynamicValidateForm"
            label-width="auto"
            class="demo-dynamic"
          >
            <el-form-item
             :style="{'margin-bottom': '18px'}"
              prop="phone"
              :rules="[
                {
                  required: true,
                  message: '请输入手机号',
                  trigger: ['blur', 'change'],
                },
              ]"
            >
              <el-input
                v-model="dynamicValidateForm.phone"
                size="large"
                :prefix-icon="User"
                placeholder="手机号"
                class="tab-input"
              />
            </el-form-item>
            
            <el-form-item
              :style="{'margin-bottom': '18px'}"
              v-if="loginMode == loginModeEnum.Forget"
              prop="verifyCode"
              :rules="[
                {
                  required: true,
                  message: '请输入验证码',
                  trigger: ['blur', 'change'],
                },
              ]"
            >
              <el-input
                v-model="dynamicValidateForm.verifyCode"
                size="large"
                :prefix-icon="User"
                placeholder="验证码"
                class="tab-input"
              >
              <template #append>
                <el-button @click="getcode(true)" class="codeb" :class="!disabled ? 'codebtn': ''" type="primary">{{disabled ? timeText+'s' : '获取验证码'}}</el-button>
              </template>
              </el-input>
            </el-form-item>

            <el-form-item
              :style="{'margin-bottom': '18px'}"
              prop="password"
              :rules="[
                {
                  required: true,
                  message: '请输入  密码',
                  trigger: ['blur', 'change'],
                },
              ]"
            >
              <el-input
                v-model="dynamicValidateForm.password"
                size="large"
                :prefix-icon="Lock"
                placeholder="密码"
                class="tab-input"
                :type="!inputtype ? 'password': ''"
              >
              <template #append>
                <el-button class="viewbtn" @click="typeclick" :icon="View" />
              </template>
              </el-input>
            </el-form-item>

            <el-form-item
            v-if="loginMode == loginModeEnum.Forget"
              :style="{'margin-bottom': '18px'}"
              prop="password1"
              :rules="[
                {
                  required: true,
                  // message: '请确认密码',
                  trigger: 'blur',
                  validator: validatePass2
                },
                
              ]"
            >
              <el-input
                v-model="dynamicValidateForm.password1"
                size="large"
                :prefix-icon="Lock"
                placeholder="确认密码"
                class="tab-input"
              />
            </el-form-item>


            <el-form-item 
              :style="{'margin-bottom': '18px'}"
              prop="type">
              <el-radio-group v-model="dynamicValidateForm.type">
                <el-radio label="研究生" :value="1"></el-radio>
                <el-radio label="农户" :value="2"></el-radio>
              </el-radio-group>
            </el-form-item>

            <el-form-item>
              <el-button 
              v-if="loginMode == loginModeEnum.Login"
              class="btn" type="primary" 
              @click="submitForm(formRef)">登 录</el-button>
              <el-button
                class="btn"
                type="primary" 
                v-if="loginMode == loginModeEnum.Forget"
                 @click="submitForm1(formRef)">
                重置密码
                </el-button>
            </el-form-item>
          </el-form>

          <div class="ttt">
            <div @click="to('/register')">新用户注册</div>
            <div v-if="loginMode == loginModeEnum.Login" @click="loginMode = loginModeEnum.Forget">忘记密码</div>
            <div v-else-if="loginMode == loginModeEnum.Forget" @click="loginMode = loginModeEnum.Login">登 录</div>
          </div>
        </div>
    </div>
    </div>

  </div>
</template>  
<script setup>
	import { Search, User, Lock, View } from '@element-plus/icons-vue';
  import { useRouter } from 'vue-router';
  import { reactive, ref } from 'vue';
  import { accountLogin, farmaccountLogin, updatePasswordByPhoneGraduateInfo, updatePasswordByPhoneFarm, sendSmsVerifyCodeFarmer, sendSmsVerifyCodeGraduate } from '@/api/home';
  import encrypt from '@/utils/cryptoUtil';

  const router = useRouter();
  const formRef = ref();
  const inputtype = ref(false);
  const dynamicValidateForm = reactive({
    phone: '',
    password: '',
    password1: '',
    verifyCode: '',
    type: 1, // 1研究生 2农户
  })
  const loginModeEnum = {
    Login: 'Login',
    Forget: 'Forget',
  }
  const loginMode = ref(loginModeEnum.Login)
  const disabled = ref(false);
  const timeText = ref(59);
  const timeout = ref(null);

  const typeclick = () => {
    console.log('222')
    inputtype.value = !inputtype.value;
  }
  const validatePass2 = (rule, value, callback) => {
    if (value === '') {
      callback(new Error('请确认登录密码'))
    } else if (value !== dynamicValidateForm.password) {
      callback(new Error("密码不一致"))
    } else {
      callback()
    }
  }

  const getcode = (isclick) => {
    console.log('123123',timeText.value)
    if(isclick) {
      if(disabled.value) {
        return
      } else {
        formRef.value?.validateField(['phone']).then(e => {
          getcodefetch();
          getcode();
        }).catch(e => {
          return
        })
      }
    } else {
      if(timeText.value === 0) {
        timeText.value = 59;
        disabled.value = false;
        clearTimeout(timeout.value)
        return
      }
      disabled.value = true;
      timeout.value = setTimeout(() => {
        if(timeText.value >0) {
          timeText.value--;
        }
        getcode();
      }, 1000);
    }

  }
  const getcodefetch = () => {
    // formEl.valida
    console.log('00formEl',formRef.value)
    // return
    formRef.value?.validateField(['phone']).then(async e => {
      const func = dynamicValidateForm?.type == 1 ? sendSmsVerifyCodeGraduate:sendSmsVerifyCodeFarmer;
      const ret = await func({phone: dynamicValidateForm.phone});
      if(ret?.code == '200') {
        _$.$message({type: 'success',message:  '验证码发送成功'});
      } 
      // else {
      //   _$.$message({type: 'error',message:  '验证码发送失败，请稍后再试'});
      // }
    })

  }
  
const submitForm = (formEl) => {
  if (!formEl) return
  formEl.validate(async(valid) => {
    if (valid) {
      console.log('submit!')
      const func = dynamicValidateForm?.type == 1 ? accountLogin: farmaccountLogin
      const ret = await func({
        params: {
          phone: dynamicValidateForm.phone,
          password: encrypt(dynamicValidateForm.password)
        }
      })
      if(ret?.code === '200') {
        _$.$message({type: 'success',message:  '登录成功'});
        if(ret?.data){
          localStorage.removeItem('userInfo_keji');
          localStorage.setItem('userInfo_keji', JSON.stringify(ret?.data))
          setTimeout(() => {
            location.href = '/'
          }, 200);
        }
      }
    } else {
      console.log('error submit!')
    }
  })
}

const submitForm1 = (formEl) => {
  if (!formEl) return
  formEl.validate(async(valid) => {
    if (valid) {
      console.log('submit!')
      const func = dynamicValidateForm?.type == 1 ? updatePasswordByPhoneGraduateInfo: updatePasswordByPhoneFarm
      const ret = await func({
        params: {
          phone: dynamicValidateForm.phone,
          password: encrypt(dynamicValidateForm.password),
          smsVerifyCode: dynamicValidateForm.verifyCode,
        }
      })
      if(ret?.code === '200') {
        _$.$message({type: 'success',message:  '登录成功'});
        // if(ret?.data){
        //   localStorage.removeItem('userInfo');
        //   localStorage.setItem('userInfo', JSON.stringify(ret?.data))
        //   setTimeout(() => {
        //     location.href = '/'
        //   }, 200);
        // }
      }
    } else {
      console.log('error submit!')
    }
  })
}


  const resetForm = (formEl) => {
    if (!formEl) return
    formEl.resetFields()
  }


  const to = (path) => {
    router.push(path)
  }

</script>
<style lang="scss" scoped>
.loginpage {
  width: 100%;
  height: 100%;
  flex: 1;
  background: url(//chengguo-1309318813.cos.ap-beijing.myqcloud.com/uploads/zizhi/1733657881212%E5%9B%BE%E5%B1%82%201.png) no-repeat center center / cover;
  overflow: hidden;
  display: flex;
  flex-direction: column;

  .l-h {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 60px 10% 0;
    align-items: center;
      .img1 {
        width: 800px;
      }
    .l-h-r {
      display: flex;
      align-items: flex-end;
      color: #fff;
      font-size: 24px;
      cursor: pointer;
      align-items: flex-end;
      height: 45px;
      img {
        margin-right: 10px;
      }
      .back {
        align-self: flex-end;
        margin-bottom: -5px;
      }
    }
  }

  .l-c {
    display: flex;
    justify-content: space-between;
    flex: 1;
    align-items: center;
    color: #fff;
    font-size: 30px;
    font-weight: normal;
    padding: 0 10%;
    .l-c-l {
      width: 900px;
      height: 700px;
      display: flex;
      flex-direction: column;
      align-items: flex-start;
      .l1 {
        font-size: 60px;
        margin-bottom: 100px;
        padding-top: 50px;
      }
      .l2 {
        font-size: 40px;
        margin-bottom: 8px;
      }
      .regis {
        margin-top: 100px;
        padding: 30px 150px;
        border-radius: 20px;
        border: 1px solid #fff;
        font-size: 40px;
        cursor: pointer;
        &:hover {
          background-color: #0a9c55;
        }
      }
    }
  }

  .login-modal {
    width: 900px;
    height: 700px;
    border-radius: 20px;
    display: flex;
    align-items: center;
    justify-content: flex-start;
    .r {
      flex: 1;
      background-color: #fff;
      height: 100%;
      display: flex;
      flex-direction: column;
      align-items: center;
      color: #1dd19d;
      padding: 0 90px;
      font-size: 36px;
      font-weight: bold;
      .divc {
        width: 100%;
        text-align: center;
        color: #333;
        font-size: 45px;
        height: 150px;
        display: flex;
        align-items: center;
        justify-content: center;
        // margin-bottom: 30px;
      }
      .divc1 {
        margin-bottom: 20px;
      }
      :deep(.el-form-item)  {
        margin-bottom: 30px;
      }
      :deep(.el-input) {
        width: 100% !important;
        justify-content: flex-start;
        // margin-bottom: 30px;
        font-size: 22px;
        height: 60px;
        .el-icon {
          color: #1dd19d;
          font-size: 20px;
        }
      }
      :deep(.btn) {
        width: 100% !important;
        height: 60px;
        background-color: #1dd19d;
        font-size: 24px;
        border: 0 none;
      }
      .ttt {
        display: flex;
        font-weight: normal;
        font-size: 22px;
        color: #999;
        display: flex;
        cursor: pointer;
        justify-content: space-between;
        align-items: center;
        height: 50px;
        width: 100%;
        margin-bottom: 10px;
        cursor: pointer;
        // margin-top: 20px;
        color: #333;
        div {
          &:hover {
            color: #1dd19d;
          }
        }
      }
    }
  }
  .codeb {
    width: 1rem;
  }
  .codebtn {
    background-color: #1dd19d;
    color: #fff;
    height: 100%;
  }
}
</style>